import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:camera_platform_interface/camera_platform_interface.dart';
import '../../event/user_account_event.dart';
import '../../event/user_id_event.dart';
import '../../http/api.dart';
import '../../main.dart';
import '../../socket/socket_manager.dart';
import '../../util/camera_util.dart';
import '../../util/toast_util.dart';
import '../auth_clipper.dart';

class AuthModel{

  RxInt step = RxInt(1);

  RxString authType = RxString('0');
  String auth =  settingEntity.auth??'1';
  SocketManager manager = SocketManager();

  CameraUtil camera = CameraUtil();
  // RxInt cameraId = RxInt(-1);
  // Timer? _timer;
  String _account = '';
  String _psw = '';


  show(){
    return Obx(() => step.value == 1?showType():show32());
  }

  showType(){
    return Container(
      margin: EdgeInsets.only(top: 10.h,left: 16.w,right: 16.w,bottom: 10.h),
      padding: EdgeInsets.all(30.r),
      width: double.infinity,
      height: 300.h,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.all(Radius.circular(4.r)),
      ),
      child: Column(
        children: [
          Text('请选择身份验证方式',style: TextStyle(color: Colors.black, fontSize: 20.sp),),
          SizedBox(height: 50.h,),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              if(auth.contains('1'))...[
                Padding(
                    padding: EdgeInsets.only(left: 10.w,right: 10.w),
                    child: InkWell(
                        onTap: (){
                          _onTap('1');
                        },
                        child: Image.asset("assets/images/reader.png",width:120.w,fit: BoxFit.fitWidth,)
                    )
                )
              ],
              if(auth.contains('2'))...[
                Padding(
                    padding: EdgeInsets.only(left: 10.w,right: 10.w),
                    child: InkWell(
                        onTap: (){
                          _onTap('2');
                        },
                        child: Image.asset("assets/images/id.png",width:120.w,fit: BoxFit.fitWidth,)
                    )
                )
              ],
              if(auth.contains('3'))...[
                Padding(
                    padding: EdgeInsets.only(left: 10.w,right: 10.w),
                    child: InkWell(
                        onTap: (){
                          _onTap('3');
                        },
                        child: Image.asset("assets/images/face.png",width:120.w,fit: BoxFit.fitWidth,)
                    )
                )
              ],
              if(auth.contains('4'))...[
                Padding(
                    padding: EdgeInsets.only(left: 10.w,right: 10.w),
                    child: InkWell(
                        onTap: (){
                          _onTap('4');
                        },
                        child: Stack(
                          alignment: AlignmentDirectional.center,
                          children: [
                            Positioned(top:6.h,child: Image.asset("assets/images/account5.png",width:104.w,fit: BoxFit.fitWidth,),),
                            Image.asset("assets/images/account1.png",width:120.w,fit: BoxFit.fitWidth,),
                            Column(
                              children: [
                                Stack(
                                  alignment: AlignmentDirectional.center,
                                  children: [
                                    Image.asset("assets/images/account2.png",width:46.w,fit: BoxFit.fitWidth,),
                                    Image.asset("assets/images/account3.png",width:20.w,fit: BoxFit.fitWidth,)

                                  ],
                                ),
                                SizedBox(height: 6.h,),

                                Image.asset("assets/images/account4.png",width:40.w,fit: BoxFit.fitWidth,),
                              ],
                            ),
                          ],
                        )
                    )
                )
              ]
            ],
          )
        ],
      ),
    );
  }

  show32(){
    if( authType.value == '0'){
      authType.value = settingEntity.auth!.substring(0,1);
    }
    return Obx(() => Container(
      margin: EdgeInsets.only(top: 10.h,left: 16.w,right: 16.w,bottom: 10.h),
      padding: EdgeInsets.all(30.r),
      width: double.infinity,
      height: 300.h,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.all(Radius.circular(4.r)),
      ),
      child: Stack(
          alignment: AlignmentDirectional.center,
          children: [
            if(authType.value == '1')...[
              Column(
                children: [
                  Text("读者卡认证",style: TextStyle(color: Colors.black,fontSize: 16.sp),),
                  SizedBox(height: 20.h,),
                  Stack(
                    alignment: AlignmentDirectional.center,
                    children: [
                      Image.asset("assets/images/mode.png",width:300.w,fit: BoxFit.fitWidth,),
                      Positioned(
                        top: 90.h,
                        right: 0,
                        child: Image.asset("assets/images/reader_mode.png",width:110.w,fit: BoxFit.fitWidth,),
                      )
                    ],
                  )
                ],
              )
            ],
            if(authType.value == '2')...[
              Column(
                children: [
                  Text("身份证认证",style: TextStyle(color: Colors.black,fontSize: 16.sp),),
                  SizedBox(height: 20.h,),
                  Stack(
                    alignment: AlignmentDirectional.center,
                    children: [
                      Image.asset("assets/images/mode.png",width:300.w,fit: BoxFit.fitWidth,),
                      Positioned(
                        top: 90.h,
                        right: 0,
                        child: Image.asset("assets/images/card.png",width:110.w,fit: BoxFit.fitWidth,),
                      )
                    ],
                  )
                ],
              )
            ],
            if(authType.value == '3')...[
              Obx(() => Column(
                children: [
                  Text("人脸认证",style: TextStyle(color: Colors.black,fontSize: 16.sp),),
                  if(camera.cameraId.value > 0)...[
                    RepaintBoundary(
                      key: _globalKey,
                      child:  ClipOval(
                        clipper: AuthClipperOvalPath(),
                        child:  Transform.scale(
                          scale:settingEntity.scale1??1,
                          child: Transform.translate(offset: Offset((settingEntity.translateX1??0).w,(settingEntity.translateY1??-100).h),
                            child: RotatedBox(
                              quarterTurns: settingEntity.rotate??0,
                              child: AspectRatio(
                                  aspectRatio: camera.getPreviewSize(),
                                  child: CameraPlatform.instance.buildPreview(camera.cameraId.value)
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
                  ]
                ],
              ))
            ],
            if(authType.value == '4')...[
              Column(
                children: [
                  Text("账号密码验证",style: TextStyle(color: Colors.black,fontSize: 16.sp),),
                  SizedBox(height: 20.h,),
                  Container(
                    width: 200.w,
                    height: 20.h,
                    margin: EdgeInsets.all(5.r),
                    child: TextField(
                      keyboardType: TextInputType.number,
                      decoration:  InputDecoration(
                        hintText: '请输入账号',
                        border:  const OutlineInputBorder(),
                        contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 0, bottom: 0).r,
                      ),
                      style: TextStyle(fontSize: 8.sp),
                      onChanged: (value){
                        _account = value;
                      },
                    ),
                  ),
                  SizedBox(height: 10.h,),
                  Container(
                    width: 200.w,
                    height: 20.h,
                    margin: EdgeInsets.all(5.r),
                    child: TextField(
                      keyboardType: TextInputType.number,
                      decoration:  InputDecoration(
                        hintText: '请输入密码',
                        border:  const OutlineInputBorder(),
                        contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 0, bottom: 0).r,
                      ),
                      style: TextStyle(fontSize: 8.sp),
                      onChanged: (value){
                        _psw = value;
                      },
                    ),
                  ),
                  SizedBox(height: 20.h,),
                  InkWell(
                    onTap: (){
                      if(_account.isEmpty || _psw.isEmpty){
                        toastWarn('账号密码不能为空');
                        return;
                      }
                      eventFactory.fire(UserIdEvent(_account,_psw));
                    },
                    child: Image.asset("assets/images/login.png", width: 200.w, fit: BoxFit.fitWidth,),
                  )
                ],
              )
            ],
            Positioned(right:10.w,bottom:20.h,child: InkWell(
              onTap: (){
                step.value = 1;
                camera.stop();
              },
              child: Image.asset("assets/images/float_back.png", width: 60.w, fit: BoxFit.fitWidth,)),
            )
          ]),
      ));
    }

  _onTap(tap) async {
    step.value = 2;
    // _timer?.cancel();
    // _timer = null;
    if(tap == '1'){
      currentTask.authType = 1;
      authType.value = '1';
      manager.setModeAndStart(Mode.reader);
      tts.speak('请刷读者卡');
    }else if(tap == '2'){
      currentTask.authType = 2;
      authType.value = '2';
      manager.setModeAndStart(Mode.identify);
      tts.speak('请刷身份证');
    }else if(tap == '3'){
      currentTask.authType = 3;
      authType.value = '3';
      manager.setModeAndStart(Mode.none);
      tts.speak('请刷人脸');
      if(camera.cameraId.value == -1){
        camera.cameraId.value = await camera.openCamera();
      }
      if(camera.cameraId.value != -1){
        camera.start((){
          _computeTakePicture();
        });
      }
    }else{
      currentTask.authType = 4;
      authType.value = '4';
      manager.setModeAndStart(Mode.none);
      tts.speak('请输入账号密码');
    }
  }

  // _start(){
  //   _timer = Timer.periodic(const Duration(seconds: 5), (timer) {
  //     // _widgetToImage();
  //     _computeTakePicture();
  //   });
  // }

  final GlobalKey _globalKey = GlobalKey();

  _computeTakePicture() async {
    CameraPlatform.instance.takePicture(camera.cameraId.value).then((XFile file){
       file.readAsBytes().then((bytes){
         String base64 = base64Encode(bytes);
         String base64Image = "data:image/png;base64,$base64";
         faceSearch(base64Image).then((data){
           File f = File.fromUri(Uri.file(file.path));
           f.delete();
           if(data.$1 != null){
             if(currentTask.uid == null){
               eventFactory.fire(UserIdEvent(data.$1.userId,null));
               // timer.cancel();
               // camera.disposeCurrentCamera();
               camera.stop();
             }
           }else{
             toastWarn('${data.$2}');
           }
         });

       });

    });

  }
  //
  // _widgetToImage() {
  //   if(_globalKey.currentContext == null){
  //     // camera.disposeCurrentCamera();
  //     _timer?.cancel();
  //     _timer = null;
  //     return;
  //   }
  //   RenderRepaintBoundary render = _globalKey.currentContext!.findRenderObject() as RenderRepaintBoundary;
  //   render.toImage().then((image){
  //     image.toByteData(format: ui.ImageByteFormat.png).then((byteData){
  //       if(byteData != null){
  //         String base64 = base64Encode(byteData.buffer.asUint8List());
  //         String base64Image = "data:image/png;base64,$base64";
  //         faceSearch(base64Image).then((data){
  //           if(data.$1 != null){
  //             if(currentTask.uid == null){
  //               eventFactory.fire(UserIdEvent(data.$1.userId));
  //               // timer.cancel();
  //               // camera.disposeCurrentCamera();
  //               _timer?.cancel();
  //               _timer = null;
  //             }
  //           }else{
  //             toastWarn('${data.$2}');
  //           }
  //         });
  //       }
  //     });
  //   });
  // }

}

